<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { SidebarTrigger } from '@/components/ui/sidebar'

// 定义帖子接口类型
interface Post {
  id: number
  title: string
  content: string
  author: string
  timestamp: string
  replies: number
}

// 定义回复接口类型
interface Reply {
  id: number
  content: string
  author: string
  timestamp: string
  postId: number
}

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const post = ref<Post | null>(null)
const replies = ref<Reply[]>([])
const newReply = ref({ content: '', author: '' })
const replyLoading = ref(false)
const loading = ref(true)
const error = ref('')
const showReplyForm = ref(false)

// 生成唯一ID
let replyIdCounter = 1

// 计算属性：按时间戳降序排列的回复列表（最新的在上方）
const sortedReplies = computed(() => {
  return [...replies.value].sort((a, b) => {
    return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
  })
})

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
  
  if (diffInSeconds < 60) {
    return '刚刚'
  } else if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60)
    return `${minutes}分钟前`
  } else if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600)
    return `${hours}小时前`
  } else if (diffInSeconds < 604800) {
    const days = Math.floor(diffInSeconds / 86400)
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// API基础URL - 连接到Spring Boot后端
const API_BASE_URL = 'http://localhost:8081/api'

// 获取帖子详情
const fetchPostDetails = async () => {
  try {
    loading.value = true
    const postId = parseInt(route.params.id as string)
    
    // 从Spring Boot后端获取帖子详情
    const postResponse = await fetch(`${API_BASE_URL}/posts/${postId}`)
    if (!postResponse.ok) {
      throw new Error('获取帖子详情失败')
    }
    const postData = await postResponse.json()
    post.value = postData
    
    // 从Spring Boot后端获取回复数据
    const repliesResponse = await fetch(`${API_BASE_URL}/posts/${postId}/replies`)
    if (!repliesResponse.ok) {
      throw new Error('获取回复数据失败')
    }
    const repliesData = await repliesResponse.json()
    replies.value = repliesData
    
    loading.value = false
  } catch (err) {
    error.value = '获取帖子详情失败'
    loading.value = false
  }
}

// 提交回复
const submitReply = async () => {
  if (!newReply.value.content || !newReply.value.author || !post.value) {
    return
  }
  
  replyLoading.value = true
  
  try {
    // 创建新回复对象
    const newReplyObj = {
      content: newReply.value.content,
      author: newReply.value.author,
      postId: post.value.id
    }
    
    // 发送回复到Spring Boot后端
    const response = await fetch(`${API_BASE_URL}/posts/${post.value.id}/replies`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newReplyObj)
    })
    
    if (!response.ok) {
      throw new Error('发布回复失败')
    }
    
    const savedReply = await response.json()
    
    // 将新回复添加到列表开头（最新的在上方）
    replies.value.unshift(savedReply)
    
    // 更新帖子回复数量
    post.value.replies += 1
    
    // 重置回复表单
    newReply.value = { content: '', author: '' }
    showReplyForm.value = false
    
  } catch (err) {
    error.value = '发布回复失败，请重试'
  } finally {
    replyLoading.value = false
  }
}

// 返回帖子列表
const goBack = () => {
  router.push('/posts')
}

// 组件挂载时获取帖子详情
onMounted(() => {
  fetchPostDetails()
})
</script>

<template>
  <div class="page">
    <!-- 头部导航 -->
    <header class="header">
      <SidebarTrigger />
      <button @click="goBack" class="back-btn">← 返回</button>
      <h1>帖子详情</h1>
    </header>

    <main class="content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        正在加载帖子详情...
      </div>

      <!-- 错误提示 -->
      <div v-else-if="error" class="error-message">
        {{ error }}
        <button @click="fetchPostDetails" class="retry-btn">重试</button>
      </div>

      <!-- 帖子详情 -->
      <div v-else-if="post" class="post-details">
        <!-- 帖子信息 -->
        <div class="post-card">
          <div class="post-header">
            <h2 class="post-title-centered">{{ post.title }}</h2>
          </div>
          <div class="post-content">
            {{ post.content }}
          </div>
          <div class="post-meta-bottom">
            <span class="author">{{ post.author }}</span>
            <span class="timestamp">{{ formatTimestamp(post.timestamp) }}</span>
            <span class="replies-count">💬 {{ post.replies }} 回复</span>
          </div>
        </div>

        <!-- 回复区域 -->
        <div class="replies-section">
          <h3>回复列表 <span class="sort-indicator">(最新回复在上方)</span></h3>
          
          <!-- 回复列表 -->
          <div v-if="sortedReplies.length > 0" class="replies-list">
            <div v-for="reply in sortedReplies" :key="reply.id" class="reply-item">
              <div class="reply-header">
                <span class="reply-author">{{ reply.author }}</span>
                <span class="reply-time">{{ formatTimestamp(reply.timestamp) }}</span>
              </div>
              <p class="reply-content">{{ reply.content }}</p>
            </div>
          </div>
          
          <!-- 无回复提示 -->
          <div v-else class="no-replies">
            暂无回复，快来抢沙发吧！
          </div>
        </div>
        
        <!-- 发表回复区域 -->
        <div class="reply-compose-section">
          <!-- 发表回复按钮 -->
          <div class="reply-toggle-section">
            <button 
              @click="showReplyForm = !showReplyForm"
              class="toggle-reply-btn"
            >
              {{ showReplyForm ? '收起' : '发表回复' }}
            </button>
          </div>
          
          <!-- 回复表单 -->
          <div v-if="showReplyForm" class="reply-form">
            <input
              type="text"
              placeholder="你的昵称"
              v-model="newReply.author"
              :disabled="replyLoading"
              required
            />
            <textarea
              placeholder="写下你的回复..."
              v-model="newReply.content"
              :disabled="replyLoading"
              required
            ></textarea>
            <button 
              @click="submitReply"
              :disabled="replyLoading || !newReply.content || !newReply.author"
              class="submit-reply-btn"
            >
              {{ replyLoading ? '发布中...' : '发布回复' }}
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: hsl(var(--background));
  color: hsl(var(--foreground));
}

.dark .page {
  background-color: #111318;
}

.content {
  flex: 1;
  padding: 2rem;
  background-color: hsl(var(--background));
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.dark .content {
  background-color: #14151d;
}

/* 头部导航样式 */
.header {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 2rem;
  border-bottom: 1px solid hsl(var(--sidebar-border));
  background: hsl(var(--sidebar-background));
  color: hsl(var(--sidebar-foreground));
}

.header h1 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: hsl(var(--sidebar-foreground));
  flex: 1;
}

.back-btn {
  background: hsl(var(--secondary));
  color: hsl(var(--secondary-foreground));
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: hsl(var(--secondary) / 0.8);
}

/* 加载状态样式 */
.loading {
  text-align: center;
  padding: 3rem;
  color: hsl(var(--muted-foreground));
  font-size: 1.1rem;
}

/* 错误提示样式 */
.error-message {
  background: #fee2e2;
  color: #dc2626;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #fecaca;
}

.dark .error-message {
  background: #7f1d1d;
  color: #fca5a5;
  border-color: #991b1b;
}

.retry-btn {
  background: #dc2626;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #b91c1c;
}

/* 帖子详情样式 */
.post-details {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.post-card {
  background: hsl(var(--card));
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  border: 1px solid hsl(var(--border));
}

.dark .post-card {
  background-color: #1e2022;
}

.post-header {
  margin-bottom: 1.5rem;
}

.post-title-centered {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  text-align: center;
}

.post-content {
  font-size: 1.1rem;
  line-height: 1.6;
  color: hsl(var(--foreground));
  margin-bottom: 1.5rem;
}

.post-meta-bottom {
  display: flex;
  gap: 1rem;
  align-items: center;
  color: hsl(var(--muted-foreground));
  font-size: 0.9rem;
  justify-content: flex-end;
}

.author {
  font-weight: 500;
  color: hsl(var(--primary));
}

/* 回复区域样式 */
.replies-section {
  background: hsl(var(--card));
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  border: 1px solid hsl(var(--border));
  margin-bottom: 2rem;
}

.dark .replies-section {
  background-color: #1e2022;
}

.replies-section h3 {
  margin: 0 0 1.5rem 0;
  font-size: 1.3rem;
  color: hsl(var(--foreground));
  border-bottom: 2px solid hsl(var(--primary));
  padding-bottom: 0.5rem;
}

.replies-list {
  margin-bottom: 2rem;
}

.reply-item {
  padding: 1rem;
  border-bottom: 1px solid hsl(var(--border));
  margin-bottom: 1rem;
}

.reply-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.reply-author {
  font-weight: 500;
  color: hsl(var(--primary));
}

.reply-time {
  color: hsl(var(--muted-foreground));
  font-size: 0.9rem;
}

.reply-content {
  margin: 0;
  line-height: 1.5;
  color: hsl(var(--foreground));
}

.no-replies {
  text-align: center;
  padding: 2rem;
  color: hsl(var(--muted-foreground));
  font-style: italic;
  margin-bottom: 2rem;
}

/* 发表回复区域 */
.reply-compose-section {
  background: hsl(var(--card));
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  border: 1px solid hsl(var(--border));
}

.dark .reply-compose-section {
  background-color: #1e2022;
}

/* 发表回复按钮区域 */
.reply-toggle-section {
  text-align: center;
}

.toggle-reply-btn {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border: none;
  padding: 1rem 2rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  font-size: 1rem;
  width: 100%;
  max-width: 300px;
  transition: all 0.3s ease;
}

.toggle-reply-btn:hover {
  background: hsl(var(--primary) / 0.9);
  transform: translateY(-2px);
}

/* 回复表单样式 */
.reply-form {
  padding-top: 2rem;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.reply-form input,
.reply-form textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid hsl(var(--border));
  border-radius: 6px;
  background: hsl(var(--background));
  color: hsl(var(--foreground));
  font-size: 1rem;
  margin-bottom: 1rem;
  transition: border-color 0.3s ease;
}

.reply-form input:focus,
.reply-form textarea:focus {
  outline: none;
  border-color: hsl(var(--primary));
}

.reply-form textarea {
  min-height: 100px;
  resize: vertical;
}

.submit-reply-btn {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
  display: block;
  margin: 0 auto;
}

.submit-reply-btn:hover {
  background: hsl(var(--primary) / 0.9);
}

.submit-reply-btn:disabled {
  background: hsl(var(--muted));
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    padding: 1rem;
  }
  
  .post-card,
  .replies-section {
    padding: 1.5rem;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}
</style>